package com.lemon.exam.common.web;

import com.lemon.exam.common.enums.CodeEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;

/**
 * 响应结果
 *
 * @author Lemon
 * @since 2024/02/17 14:46
 */
@Slf4j
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> implements Serializable {
    @Schema(description = "是否成功")
    private boolean success;

    @Schema(description = "响应码（CodeEnum.SUCCESS.getCode()表示成功）")
    private int code;

    @Schema(description = "响应的数据")
    private T data;

    @Schema(description = "响应的信息")
    private String message;

    /**
     * 构建返回结果
     *
     * @param success
     * @param code
     * @param data
     * @param message
     * @param <T>
     * @return
     */
    private static <T> Result<T> build(boolean success, int code, T data, String message) {
        return new Result<>(success, code, data, message);
    }

    /**
     * 默认响应成功的返回
     *
     * @param <T>
     * @return
     */
    public static <T> Result<T> ok() {
        return build(true, CodeEnum.SUCCESS.getCode(), null, null);
    }

    /**
     * 响应成功带返回数据
     *
     * @param <T>
     * @return
     */
    public static <T> Result<T> ok(T data) {
        return build(true, CodeEnum.SUCCESS.getCode(), data, null);
    }

    /**
     * 默认响应失败的返回
     *
     * @param <T>
     * @return
     */
    public static <T> Result<T> err() {
        return build(false, CodeEnum.ERROR_500.getCode(), null, null);
    }

    /**
     * 响应失败的返回
     *
     * @param <T>
     * @return
     */
    public static <T> Result<T> err(String message) {
        return build(false, CodeEnum.ERROR_500.getCode(), null, message);
    }

    /**
     * 响应失败的返回，带状态码
     *
     * @param <T>
     * @return
     */
    public static <T> Result<T> err(int code, String message) {
        return build(false, code, null, message);
    }

    /**
     * 响应失败的返回，带状态码
     *
     * @param <T>
     * @return
     */
    public static <T> Result<T> err(CodeEnum codeEnum) {
        return build(false, codeEnum.getCode(), null, codeEnum.getMessage());
    }
}
